package instruct

import "go_jvm/thread"

type Instruction interface {
	// 提取操作数
	FetchOperands(reader *ByteCodeReader)
	// 执行指令
	Execute(frame *thread.Frame)
	// 操作码
	OperationCode() int
}

type ByteCodeReader interface {
	ReadInt16() int16
	ReadUInt8() uint8
	ReadUInt16() uint16
	Reset(code []byte, pc int)
	ReadInt8() int8
}

type ByteCodeReaderImpl struct {
	code []byte
	pc   int
}

func (self *ByteCodeReaderImpl) Reset(code []byte, pc int) {
	self.code = code
	self.pc = pc
}

func (self *ByteCodeReaderImpl) ReadInt16() int16 {
	return int16(self.ReadUInt16())
}

func (self *ByteCodeReaderImpl) ReadInt8() int8 {
	return int8(self.ReadUInt8())
}

func (self *ByteCodeReaderImpl) ReadUInt8() uint8 {
	i := self.code[self.pc]
	self.pc++
	return i
}

func (self *ByteCodeReaderImpl) ReadUInt16() uint16 {
	i1 := uint16(self.code[self.pc])
	i2 := uint16(self.code[self.pc+1])
	self.pc += 2
	return i1<<8 | i2
}

func (self *ByteCodeReaderImpl) ReadUInt32() int32 {
	i1 := int32(self.code[self.pc])
	i2 := int32(self.code[self.pc+1])
	i3 := int32(self.code[self.pc+2])
	i4 := int32(self.code[self.pc+3])
	self.pc += 4
	return (i1 << 24) | (i2 << 16) | (i3 << 8) | i4
}

// 没有操作数的指令
type NoOperandsInstruction struct {
}

func (self *NoOperandsInstruction) FetchOperands(reader *ByteCodeReader) {
	//do noting
}

// 跳转指令
type BranchInstruction struct {
	Offset int
}

func (self *BranchInstruction) FetchOperands(reader *ByteCodeReader) {
	self.Offset = int((*reader).ReadInt16())
}
func (self *BranchInstruction) Execute(frame *thread.Frame) {

}

// 根据索引存取局部变量
type Int8Instruction struct {
	Offset uint8
}

func (self *Int8Instruction) FetchOperands(reader *ByteCodeReader) {
	self.Offset = (*reader).ReadUInt8()
}

// 根据索引存取局部变量
type Index16Instruction struct {
	Offset uint16
}

func (self *Index16Instruction) FetchOperands(reader *ByteCodeReader) {
	self.Offset = (*reader).ReadUInt16()
}
func (self *Index16Instruction) Execute(frame *thread.Frame) {

}
